﻿using ProjectFootball.MVC.Foundation;
using ProjectFootball.MVC.Foundation.Repositories;
using ProjectFootball.MVC.Models.EntityFramework.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;

namespace ProjectFootball.MVC.Models.RepositoryProviders
{
    public static class PersonRepositoryExtensions
    {
        public static IEnumerable<string> GetAutoCompleteList(this IDataRepository<Person> personRepository, IPrincipal user, string searchText)
        {
            var people = from p in personRepository
                         where (p.Forenames + " " + p.Surname).Contains(searchText)
                         select p;

            return people.AsEnumerable().Where(p => p.CanView(user)).Select(p => p.FullName).Distinct().OrderBy(p => p);
        }

        public static IEnumerable<ICodePickerData> GetCodePickerData(this IDataRepository<Person> personRepository)
        {
            return personRepository
                .Where(c => c.IsApproved)
                .OrderBy(c => c.Surname)
                .ThenBy(c => c.Forenames)
                .AsEnumerable()
                .Select(c =>
                    new GuidCodePicker()
                    {
                        Code = c.Pk,
                        Description = c.FullName
                    });
        }

        public static Person SearchByPrimaryKey(this IDataRepository<Person> personRepository, Guid id)
        {
            var people = from c in personRepository
                               where c.Pk == id
                               select c;

            return people.Any() ? people.Single() : null;
        }
    }
}